<template>
  <div class="layout-container">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <h2>房屋租赁系统</h2>
      </div>
      <div class="header-right">
        <span>欢迎您，{{ username }}</span>
      </div>
    </el-header>

    <el-container class="main-container">
      <!-- 左侧导航栏 -->
      <el-aside width="250px" class="aside">
        <!-- 用户信息卡片 -->
        <div class="user-info">
          <el-avatar :size="64" :src="userAvatar">
            <img src="/src/assets/default-avatar.png"/>
          </el-avatar>
          <h3>{{ username }}</h3>
          <el-button type="primary" size="small" @click="goToProfile">修改个人信息</el-button>
          <el-button type="danger" size="small" @click="handleLogout">退出登录</el-button>
        </div>

        <el-menu
          default-active="2-5"
          class="menu"
          background-color="#304156"
          text-color="#fff"
          active-text-color="#409EFF"
          @select="handleMenuSelect"
        >
          <el-sub-menu index="1">
            <template #title>
              <el-icon><User /></el-icon>
              <span>我是租客</span>
            </template>
            <el-menu-item index="1-1">我的收藏</el-menu-item>
            <el-menu-item index="1-2">消息列表</el-menu-item>
            <el-menu-item index="1-3">我的预约</el-menu-item>
            <el-menu-item index="1-4">我的订单</el-menu-item>
            <el-menu-item index="1-5">我的租房</el-menu-item>
          </el-sub-menu>

          <el-sub-menu index="2">
            <template #title>
              <el-icon><House /></el-icon>
              <span>我是房东</span>
            </template>
            <el-menu-item index="2-1">我要出租</el-menu-item>
            <el-menu-item index="2-2">消息列表</el-menu-item>
            <el-menu-item index="2-3">管理出租</el-menu-item>
            <el-menu-item index="2-4">预约反馈</el-menu-item>
            <el-menu-item index="2-5">维修反馈</el-menu-item>
            <el-menu-item index="2-6">租金收入</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>

      <!-- 主要内容区域 -->
      <el-main class="main">
        <div class="maintenance-feedback">
          <el-card class="main-card">
            <template #header>
              <div class="card-header">
                <span>维修反馈管理</span>
                <el-button type="primary" size="small" @click="fetchMaintenanceRequests">刷新数据</el-button>
              </div>
            </template>
            
            <!-- 搜索和筛选区域 -->
            <div class="search-container">
              <el-select v-model="statusFilter" placeholder="处理状态" clearable>
                <el-option label="全部" value=""></el-option>
                <el-option label="待处理" value="待处理"></el-option>
                <el-option label="处理中" value="处理中"></el-option>
                <el-option label="已完成" value="已完成"></el-option>
                <el-option label="已取消" value="已取消"></el-option>
              </el-select>
              
              <el-button type="primary" @click="searchMaintenanceRequests">搜索</el-button>
            </div>
            
            <!-- 维修请求列表表格 -->
            <el-table
              :data="maintenanceList"
              style="width: 100%"
              border
              stripe
              v-loading="loading"
            >
              <el-table-column prop="request_id" label="请求ID" width="80" />
              <el-table-column prop="tenant_name" label="租户姓名" width="120" />
              <el-table-column prop="house_address" label="房屋地址" min-width="150" show-overflow-tooltip />
              <el-table-column prop="content" label="维修内容" min-width="200" show-overflow-tooltip />
              <el-table-column prop="submitted_at" label="提交时间" width="180" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getStatusTag(scope.row.status)">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button size="small" @click="viewMaintenanceDetails(scope.row)">查看</el-button>
                  <el-button 
                    size="small" 
                    type="primary" 
                    v-if="scope.row.status === '待处理'"
                    @click="startProcessing(scope.row)"
                  >
                    开始处理
                  </el-button>
                  <el-button 
                    size="small" 
                    type="success" 
                    v-if="scope.row.status === '处理中'"
                    @click="completeProcessing(scope.row)"
                  >
                    完成处理
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                :current-page="currentPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>

    <!-- 维修详情对话框 -->
    <el-dialog
      v-model="maintenanceDetailVisible"
      title="维修详情"
      width="600px"
    >
      <div v-if="currentMaintenance" class="maintenance-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="请求ID">{{ currentMaintenance.request_id }}</el-descriptions-item>
          <el-descriptions-item label="租户姓名">{{ currentMaintenance.tenant_name }}</el-descriptions-item>
          <el-descriptions-item label="房屋地址">{{ currentMaintenance.house_address }}</el-descriptions-item>
          <el-descriptions-item label="维修内容">{{ currentMaintenance.content }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ formatDateTime(currentMaintenance.submitted_at) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTag(currentMaintenance.status)">
              {{ currentMaintenance.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentMaintenance.processed_at" label="处理时间">
            {{ formatDateTime(currentMaintenance.processed_at) }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentMaintenance.result_notes" label="处理结果">
            {{ currentMaintenance.result_notes }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="currentMaintenance.status === '待处理'" class="action-buttons">
          <el-button type="primary" @click="startProcessing(currentMaintenance)">开始处理</el-button>
        </div>
        
        <div v-if="currentMaintenance.status === '处理中'" class="result-form">
          <h4>处理结果</h4>
          <el-form>
            <el-form-item>
              <el-input
                v-model="resultNotes"
                type="textarea"
                :rows="4"
                placeholder="请输入处理结果"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="completeProcessing(currentMaintenance)">完成处理</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { User, House } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
// 从localStorage获取用户名
const username = ref('')
const userAvatar = ref('')

const loading = ref(false)
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const maintenanceList = ref([])
const maintenanceDetailVisible = ref(false)
const currentMaintenance = ref(null)
const resultNotes = ref('')

// 获取状态标签样式
const getStatusTag = (status) => {
  const statusMap = {
    '待处理': 'danger',
    '处理中': 'warning',
    '已完成': 'success',
    '已取消': 'info'
  }
  return statusMap[status] || 'info'
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString()
}

// 获取维修请求列表
const fetchMaintenanceRequests = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://127.0.0.1:5000/api/landlord/maintenance', {
      params: {
        page: currentPage.value,
        per_page: pageSize.value,
        status: statusFilter.value
      },
      headers: {
        'Authorization': `${localStorage.getItem('token')}`
      }
    })
    
    if (response.data.status === 200) {
      maintenanceList.value = response.data.data.maintenance_requests
      total.value = response.data.data.total
    } else {
      ElMessage.error(response.data.msg || '获取维修请求列表失败')
    }
  } catch (error) {
    console.error('获取维修请求列表失败:', error)
    ElMessage.error('获取维修请求列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索维修请求
const searchMaintenanceRequests = () => {
  currentPage.value = 1
  fetchMaintenanceRequests()
}

// 查看维修详情
const viewMaintenanceDetails = (maintenance) => {
  currentMaintenance.value = maintenance
  resultNotes.value = maintenance.result_notes || ''
  maintenanceDetailVisible.value = true
}

// 开始处理维修请求
const startProcessing = (maintenance) => {
  ElMessageBox.confirm(
    '确定要开始处理该维修请求吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await axios.put(`http://127.0.0.1:5000/api/landlord/maintenance/${maintenance.request_id}`, {
        status: '处理中'
      }, {
        headers: {
          // 'Authorization': `Bearer ${localStorage.getItem('token')}`
           'Authorization': `${localStorage.getItem('token')}`
        }
      })
      
      if (response.data.status === 200) {
        // 更新本地数据
        const index = maintenanceList.value.findIndex(m => m.request_id === maintenance.request_id)
        if (index !== -1) {
          maintenanceList.value[index].status = '处理中'
        }
        
        // 更新当前查看的维修请求
        if (currentMaintenance.value && currentMaintenance.value.request_id === maintenance.request_id) {
          currentMaintenance.value.status = '处理中'
        }
        
        ElMessage.success('已开始处理维修请求')
      } else {
        ElMessage.error(response.data.msg || '操作失败')
      }
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 完成处理维修请求
const completeProcessing = (maintenance) => {
  if (maintenance.status === '处理中' && !resultNotes.value.trim()) {
    ElMessage.warning('请输入处理结果')
    return
  }
  
  ElMessageBox.confirm(
    '确定要完成处理该维修请求吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await axios.put(`http://127.0.0.1:5000/api/landlord/maintenance/${maintenance.request_id}`, {
        status: '已完成',
        result_notes: resultNotes.value
      }, {
        headers: {
          'Authorization': `${localStorage.getItem('token')}`
        }
      })
      
      if (response.data.status === 200) {
        // 更新本地数据
        const index = maintenanceList.value.findIndex(m => m.request_id === maintenance.request_id)
        if (index !== -1) {
          maintenanceList.value[index].status = '已完成'
          maintenanceList.value[index].result_notes = resultNotes.value
          maintenanceList.value[index].processed_at = response.data.data.processed_at
        }
        
        // 更新当前查看的维修请求
        if (currentMaintenance.value && currentMaintenance.value.request_id === maintenance.request_id) {
          currentMaintenance.value.status = '已完成'
          currentMaintenance.value.result_notes = resultNotes.value
          currentMaintenance.value.processed_at = response.data.data.processed_at
        }
        
        ElMessage.success('维修请求已完成处理')
        maintenanceDetailVisible.value = false
      } else {
        ElMessage.error(response.data.msg || '操作失败')
      }
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchMaintenanceRequests()
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchMaintenanceRequests()
}

// 处理菜单选择
const handleMenuSelect = (index) => {
  switch(index) {
    // 房东相关菜单
    case '2-4': // 预约反馈
      router.push('/landlord/appointment')
      break
    case '2-5': // 维修反馈
      router.push('/landlord/maintenance')
      break
    case '2-6': // 租金收入
      router.push('/landlord/income')
      break
    // 其他菜单项的处理...
    default:
      router.push('/user')
      break
  }
}

// 处理退出登录
const handleLogout = () => {
  ElMessageBox.confirm(
    '确定要退出登录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 清除本地存储的信息
    localStorage.removeItem('token')
    localStorage.removeItem('userId')
    localStorage.removeItem('isAdmin')
    localStorage.removeItem('username')
    localStorage.removeItem('userAvatar')
    
    ElMessage.success('已成功退出登录')
    router.push('/login')
  }).catch(() => {
    // 取消退出登录
  })
}

// 打开个人信息修改弹窗
const goToProfile = () => {
  router.push('/user')
}

onMounted(() => {
  // 获取登录时存储的用户信息
  username.value = localStorage.getItem('username') || '用户'
  userAvatar.value = localStorage.getItem('userAvatar') || ''
  fetchMaintenanceRequests()
})
</script>

<style scoped>
.layout-container {
  height: 100vh;
  background-color: #f0f2f5;
}

.header {
  background-color: #409EFF; /* 修改背景颜色为蓝色 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
}

.header-left h2 {
  color: #fff; /* 修改文字颜色为白色 */
  margin: 0;
}

.header-right span {
  color: #fff; /* 修改文字颜色为白色 */
}

.main-container {
  height: calc(100vh - 60px);
}

.aside {
  background-color: #304156;
  height: 100%;
}

.menu {
  border-right: none;
}

.user-info {
  padding: 20px;
  text-align: center;
  background-color: #263445;
  color: #fff;
}

.user-info h3 {
  margin: 10px 0;
  font-size: 16px;
  color: #fff;
}

.user-info .el-button {
  margin-top: 10px;
}

.main {
  padding: 20px;
  background-color: #f0f2f5;
  overflow-y: auto;
}

.maintenance-feedback {
  width: 100%;
}

.main-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.maintenance-detail {
  padding: 10px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.result-form {
  margin-top: 20px;
}

.result-form h4 {
  margin-bottom: 10px;
  color: #409EFF;
}
</style>